<?php

namespace app\api\controller;

use app\common\controller\ApiController;
use app\common\model\Artifact;
use app\common\model\User;
use think\Db;
use think\Env;
use think\Request;

/**
 * 录音音色接口
 */
class Speaker extends ApiController
{
    protected $noNeedLogin = ['save'];
    protected $noNeedRight = '*';
    protected $tableName = 'speaker';
    protected $fields = false;
    protected $fieldsExcept = false;
    protected $onlySelf = true;
    protected $orderBy = 'id desc';
    protected $conditions = [
        'deletetime' => null,
    ];
    protected $defaultPageSize = 10;

    protected function processData($method, $data)
    {
        if ($method === 'beforeList') {
                      
        }
        if ($method === 'afterList') {
             // 添加 image_url
            $artifactModel = new Artifact();    
            $artifact = $artifactModel->getAllArtifact($this->getRedis());
            
            // 修复：使用 array_walk 或 array_map 替代 each() 方法
            $data = collection($data)->each(function ($item) use ($artifact) {
                // 如果 $item['artifact_id'] 为空，则 image_url 也设置为空
                $item['image_url'] = !empty($item['artifact_id']) && isset($artifact[$item['artifact_id']]) ? $artifact[$item['artifact_id']]['image_url'] : '';
                return $item;
            });
        }
        return $data;
    }

    protected function paging()
    {
        $page = $this->request->param('page', 1);
        $pageSize = $this->request->param('pageSize', $this->defaultPageSize ?? 10);
        $pageSize = $pageSize > 100 ? 100 : $pageSize;
        $offset = ($page - 1) * $pageSize;
        return [$offset, $pageSize];
    }

    

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $this->onlySelf = false;
        $data = $this->request->param('', null, $this->paramFilter);
        // 验证签名
        $userId = $data['user_id'];
        $this->checkSign($request, $userId);
        $user = User::get($userId);


        Db::startTrans();

        try {            
            $data['createtime'] = time();
            $data = $this->processData('beforeSave', $data);
        } catch (\think\exception\ErrorException $e) {
            $msg = $e->getMessage();
            $file = $e->getFile();
            $line = $e->getLine();
            trace("msg: $msg | file: $file | line: $line", 'error');
            Db::rollback();
            $this->fail(__('Failed to update data'));
        }

        if ($this->onlySelf) {
            $user = $this->auth->getUser();
            $data['user_id'] = $user->id;
        }

        try {
            $id = Db::name($this->tableName)->insertGetId($data);
            if (!$id) {
                $this->fail(__('Failed to update data'));
            }
            $data['id'] = $id;
            $data = $this->processData('afterSave', $data);
            Db::commit();
        } catch (\think\exception\ErrorException $e) {
            $msg = $e->getMessage();
            $file = $e->getFile();
            $line = $e->getLine();
            Db::rollback();
            trace("msg: $msg | file: $file | line: $line", 'error');
            $this->fail(__('Failed to update data'));
        } catch (\think\Exception $e) {
            $msg = $e->getMessage();
            trace("msg: $msg", 'error');
            Db::rollback();
            $this->fail(__('Failed to update data'));
        }

        return $this->success('', $data);
    }

    private function checkSign($request, $userId)
    {
        $key = Env::get('api.signature_key');
        if (!$userId) {
            $this->fail(__('user_id is missing'));
        }
        if (!$key) {
            $this->fail(__('Signature key is missing'));
        }
        $sign = md5($key . $userId);
        // 从header中的signature获取签名
        $signature = $request->header('signature');
        if (!$signature) {
            $this->fail(__('header signature is missing'));
        }
        if ($signature !== $sign) {
            $this->fail(__('Signature verification failed'));
        }
    }   
    
}
